"""
系统权限初始化脚本
用于在数据库中创建基础的权限和角色数据
"""
from common.database import DatabaseManager
from common.logger import create_logger

logger = create_logger("permission_init")


def init_permissions():
    """
    初始化系统基础权限
    """
    db = DatabaseManager()

    try:
        # 创建基础权限数据
        permissions = [
            # 系统管理
            ("system:admin", "系统管理员", "API", 0, "/system", 1, 1),

            # 用户管理
            ("system:user:manage", "用户管理", "API", 1, "/system/users", 2, 1),
            ("system:user:create", "创建用户", "API", 2, "/system/users/create", 3, 2),
            ("system:user:update", "更新用户", "API", 2, "/system/users/update", 3, 3),
            ("system:user:delete", "删除用户", "API", 2, "/system/users/delete", 3, 4),
            ("system:user:view", "查看用户", "API", 2, "/system/users/view", 3, 5),

            # 角色管理
            ("system:role:manage", "角色管理", "API", 1, "/system/roles", 2, 2),
            ("system:role:create", "创建角色", "API", 3, "/system/roles/create", 3, 1),
            ("system:role:update", "更新角色", "API", 3, "/system/roles/update", 3, 2),
            ("system:role:delete", "删除角色", "API", 3, "/system/roles/delete", 3, 3),
            ("system:role:view", "查看角色", "API", 3, "/system/roles/view", 3, 4),
            ("system:role:assign", "分配角色", "API", 3, "/system/roles/assign", 3, 5),

            # 权限管理
            ("system:permission:manage", "权限管理", "API", 1, "/system/permissions", 2, 3),
            ("system:permission:create", "创建权限", "API", 4, "/system/permissions/create", 3, 1),
            ("system:permission:update", "更新权限", "API", 4, "/system/permissions/update", 3, 2),
            ("system:permission:delete", "删除权限", "API", 4, "/system/permissions/delete", 3, 3),
            ("system:permission:view", "查看权限", "API", 4, "/system/permissions/view", 3, 4),

            # 审计日志
            ("system:audit:view", "查看审计日志", "API", 1, "/system/audit-logs", 2, 4),
            ("system:audit:export", "导出审计日志", "API", 5, "/system/audit-logs/export", 3, 1),

            # 业务权限
            ("device:manage", "设备管理", "API", 0, "/devices", 1, 2),
            ("device:view", "查看设备", "API", 6, "/devices/view", 2, 1),
            ("device:create", "创建设备", "API", 6, "/devices/create", 2, 2),
            ("device:update", "更新设备", "API", 6, "/devices/update", 2, 3),
            ("device:delete", "删除设备", "API", 6, "/devices/delete", 2, 4),

            ("alarm:manage", "告警管理", "API", 0, "/alarms", 1, 3),
            ("alarm:view", "查看告警", "API", 7, "/alarms/view", 2, 1),
            ("alarm:handle", "处理告警", "API", 7, "/alarms/handle", 2, 2),

            ("work_order:manage", "工单管理", "API", 0, "/work-orders", 1, 4),
            ("work_order:view", "查看工单", "API", 8, "/work-orders/view", 2, 1),
            ("work_order:create", "创建工单", "API", 8, "/work-orders/create", 2, 2),
            ("work_order:update", "更新工单", "API", 8, "/work-orders/update", 2, 3),
            ("work_order:assign", "分配工单", "API", 8, "/work-orders/assign", 2, 4),

            ("region:view", "查看区域", "API", 0, "/regions", 1, 5),
            ("file:manage", "文件管理", "API", 0, "/files", 1, 6),
            
            # 数据分析权限
            ("analytics:view", "查看数据分析", "API", 0, "/analytics", 1, 7),
            ("analytics:consumption", "用量统计", "API", 9, "/analytics/consumption", 2, 1),
            ("analytics:alarms", "告警统计", "API", 9, "/analytics/alarms", 2, 2),
            ("analytics:inventory", "设备资产统计", "API", 9, "/analytics/inventory", 2, 3),
        ]

        # 插入权限数据
        for perm in permissions:
            # 检查权限是否已存在
            existing = db.execute_query(
                "SELECT id FROM base_permission WHERE perm_code = %s",
                (perm[0],)
            )

            if not existing:
                db.execute_query(
                    """
                    INSERT INTO base_permission (perm_code, perm_name, type, parent_id, path, level, sort, deleted,
                                                 gmt_create)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, 0, NOW())
                    """,
                    perm,
                    commit=True
                )
                logger.info(f"创建权限: {perm[0]} - {perm[1]}")
            else:
                logger.info(f"权限已存在: {perm[0]} - {perm[1]}")

    except Exception as e:
        logger.error(f"初始化权限失败: {e}")
        raise
    finally:
        db.close()


def init_roles():
    """
    初始化系统基础角色
    """
    db = DatabaseManager()

    try:
        # 创建基础角色
        roles = [
            ("SUPER_ADMIN", "超级管理员", "系统超级管理员，拥有所有权限", "SYSTEM"),
            ("ADMIN", "系统管理员", "系统管理员，负责用户和权限管理", "SYSTEM"),
            ("OPERATOR", "操作员", "系统操作员，负责日常业务操作", "CUSTOM"),
            ("VIEWER", "查看者", "只读用户，只能查看数据", "CUSTOM"),
        ]

        role_ids = {}

        # 插入角色数据
        for role in roles:
            # 检查角色是否已存在
            existing = db.execute_query(
                "SELECT id FROM base_role WHERE role_code = %s",
                (role[0],)
            )

            if not existing:
                result = db.execute_query(
                    """
                    INSERT INTO base_role (role_code, role_name, description, type, enabled, deleted, version,
                                           gmt_create, gmt_update)
                    VALUES (%s, %s, %s, %s, 1, 0, 1, NOW(), NOW())
                    """,
                    role,
                    commit=True
                )
                role_id = db.connection.cursor().lastrowid
                role_ids[role[0]] = role_id
                logger.info(f"创建角色: {role[0]} - {role[1]}")
            else:
                role_ids[role[0]] = existing[0]["id"]
                logger.info(f"角色已存在: {role[0]} - {role[1]}")

        # 为超级管理员分配所有权限
        if "SUPER_ADMIN" in role_ids:
            role_id = role_ids["SUPER_ADMIN"]
            if role_id is not None:
                # 获取所有权限
                permissions = db.execute_query("SELECT id FROM base_permission WHERE deleted = 0")

                for perm in permissions:
                    # 检查权限关系是否已存在
                    existing = db.execute_query(
                        "SELECT 1 FROM base_role_permission WHERE role_id = %s AND perm_id = %s",
                        (role_id, perm["id"])
                    )

                    if not existing:
                        db.execute_query(
                            "INSERT INTO base_role_permission (role_id, perm_id) VALUES (%s, %s)",
                            (role_id, perm["id"]),
                            commit=True
                        )

                logger.info(f"为超级管理员分配了 {len(permissions)} 个权限")
            else:
                logger.warning("超级管理员角色ID为空，无法分配权限")

        # 为系统管理员分配基础管理权限
        if "ADMIN" in role_ids:
            role_id = role_ids["ADMIN"]
            if role_id is not None:
                admin_permissions = [
                    "system:user:manage", "system:role:manage", "system:permission:manage",
                    "system:audit:view", "device:view", "alarm:view", "work_order:view", "region:view"
                ]

                for perm_code in admin_permissions:
                    perm_result = db.execute_query(
                        "SELECT id FROM base_permission WHERE perm_code = %s",
                        (perm_code,)
                    )

                    if perm_result and len(perm_result) > 0:
                        perm_id = perm_result[0]["id"]
                        if perm_id is not None:
                            existing = db.execute_query(
                                "SELECT 1 FROM base_role_permission WHERE role_id = %s AND perm_id = %s",
                                (role_id, perm_id)
                            )

                            if not existing:
                                db.execute_query(
                                    "INSERT INTO base_role_permission (role_id, perm_id) VALUES (%s, %s)",
                                    (role_id, perm_id),
                                    commit=True
                                )

                logger.info(f"为系统管理员分配了管理权限")
            else:
                logger.warning("系统管理员角色ID为空，无法分配权限")

        # 为操作员分配告警处理权限
        if "OPERATOR" in role_ids:
            role_id = role_ids["OPERATOR"]
            if role_id is not None:
                operator_permissions = [
                    "alarm:manage", "alarm:view", "alarm:handle",
                    "work_order:view", "work_order:update",
                    "analytics:view", "analytics:consumption", "analytics:alarms"
                ]

                for perm_code in operator_permissions:
                    perm_result = db.execute_query(
                        "SELECT id FROM base_permission WHERE perm_code = %s",
                        (perm_code,)
                    )

                    if perm_result and len(perm_result) > 0:
                        perm_id = perm_result[0]["id"]
                        if perm_id is not None:
                            existing = db.execute_query(
                                "SELECT 1 FROM base_role_permission WHERE role_id = %s AND perm_id = %s",
                                (role_id, perm_id)
                            )

                            if not existing:
                                db.execute_query(
                                    "INSERT INTO base_role_permission (role_id, perm_id) VALUES (%s, %s)",
                                    (role_id, perm_id),
                                    commit=True
                                )

                logger.info(f"为操作员分配了告警处理权限")
            else:
                logger.warning("操作员角色ID为空，无法分配权限")

    except Exception as e:
        logger.error(f"初始化角色失败: {e}")
        raise
    finally:
        db.close()


def create_admin_user():
    """
    创建默认管理员用户
    """
    db = DatabaseManager()

    try:
        from app.common.security import hash_password
        from datetime import datetime

        # 检查是否已存在管理员用户
        existing = db.execute_query(
            "SELECT id FROM base_user WHERE username = %s",
            ("admin",)
        )

        if not existing:
            # 生成用户编码（使用与user_crud中相同的逻辑）
            from datetime import datetime

            date_str = datetime.now().strftime("%Y%m%d")
            prefix = f"U{date_str}"

            # 查询当天最大的流水号
            result = db.execute_query(
                "SELECT user_code FROM base_user WHERE user_code LIKE %s ORDER BY user_code DESC LIMIT 1",
                (f"{prefix}%",)
            )

            if result and result[0]["user_code"]:
                # 提取流水号并加1
                last_code = result[0]["user_code"]
                sequence = int(last_code[-6:]) + 1
            else:
                # 当天第一个用户
                sequence = 1

            # 生成6位流水号
            sequence_str = str(sequence).zfill(6)
            user_code = f"{prefix}{sequence_str}"

            # 创建管理员用户
            db.execute_query(
                """
                INSERT INTO base_user (user_code, username, name, email, phone, hashed_password, disabled, created_at,
                                       updated_at, deleted)
                VALUES (%s, %s, %s, %s, %s, %s, 0, NOW(), NOW(), 0)
                """,
                (user_code, "admin", "系统管理员", "admin@example.com", "13800000000", hash_password("admin123")),
                commit=True
            )

            # 为管理员分配超级管理员角色
            super_admin_role = db.execute_query(
                "SELECT id FROM base_role WHERE role_code = %s",
                ("SUPER_ADMIN",)
            )

            if super_admin_role and len(super_admin_role) > 0:
                role_id = super_admin_role[0]["id"]
                if role_id is not None:
                    db.execute_query(
                        "INSERT INTO base_user_role (user_code, role_id) VALUES (%s, %s)",
                        (user_code, role_id),
                        commit=True
                    )
                    logger.info(f"为管理员用户分配了超级管理员角色")
                else:
                    logger.warning("超级管理员角色ID为空，无法分配角色")
            else:
                logger.warning("未找到超级管理员角色，无法分配角色")

            logger.info(f"创建管理员用户: admin, 密码: admin123")
        else:
            logger.info("管理员用户已存在")

    except Exception as e:
        logger.error(f"创建管理员用户失败: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    logger.info("开始初始化系统权限数据...")

    try:
        # 1. 初始化权限
        logger.info("初始化权限...")
        init_permissions()

        # 2. 初始化角色
        logger.info("初始化角色...")
        init_roles()

        # 3. 创建管理员用户
        logger.info("创建管理员用户...")
        create_admin_user()

        logger.info("系统权限数据初始化完成！")
        print("初始化完成！默认管理员账号：admin，密码：admin123")

    except Exception as e:
        logger.error(f"初始化失败: {e}")
        print(f"初始化失败: {e}")